package com.coderman.spring.aopscale.context;

import com.coderman.spring.aopscale.beans.RequestLogicBean;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * Created  on 2018-9-27.
 *
 * @author: fanchunshuai
 * @version: V1.0
 * @Desc:
 */
@Component
public class RequestBusLogicContext {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 扫描注解：RequestLogic中的属性，
     * key:方法上带有RequestLogic注解的类路径,egg:com.xx.xxImpl.xxMethod，转换为hash值作为key
     * value:与注解RequestLogic对应的RequestLogicBean实体
     * 适用于http接口层
     */
    private Map<Integer, RequestLogicBean> baseBusLogicMap = new HashMap<>();


    @Autowired
    private InnerBusLogicContext innerBusLogicContext;



    public Map<Integer, RequestLogicBean> getRequestLogicMap() {
        return baseBusLogicMap;
    }


   /* *//**
     * 获取调用方法的key的hash值
     *
     * @return
     */
    public String getHashKey(JoinPoint joinPoint) {
        String key = innerBusLogicContext.getKey(joinPoint);
        String tmpKey = innerBusLogicContext.getTmpKey(joinPoint, key);
        logger.debug("inner BusLog key = {},tmpKey = {}", key, tmpKey);
        return key;
    }

    /**
     * 获取调用方法的key的hash值
     *
     * @return
     */
    public String getTmpKey(JoinPoint joinPoint) {
        String key = innerBusLogicContext.getKey(joinPoint);
        String tmpKey = innerBusLogicContext.getTmpKey(joinPoint, key);
        logger.debug("inner BusLog key = {},tmpKey = {}", key, tmpKey);
        return tmpKey;
    }

    /**
     * 根据上下文获取业务逻辑bean
     *
     * @return
     */
    public RequestLogicBean getLogicBean(String key) {
        if (StringUtils.isBlank(key)) {
            return null;
        }
        int hashKey = key.hashCode();
        RequestLogicBean baseBusLogicBean = this.getRequestLogicMap().get(hashKey);
        if (baseBusLogicBean == null) {
            return null;
        }
        return baseBusLogicBean;
    }
}
